package com.situ.day22;

import com.situ.day5.Person;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

public class ReflectDemo {

    @Test
    public void test1() throws ClassNotFoundException {
        //1. Class.forName(完整的包名+类名);
        Class clazz1 = Class.forName("com.situ.day22.Student");
        //2. 类名.class
        Class clazz2 = Student.class;
        //3.对象.getClass();
        Student student = new Student();
        Class clazz3 = student.getClass();

        System.out.println(clazz1 == clazz2);//true
        System.out.println(clazz1 == clazz3);//true
        System.out.println(clazz2 == clazz3);//true
    }

    @Test
    public void testConstructor() {
        Class clazz = Student.class;
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
            System.out.println(constructor.getName());//构造方法名字
            System.out.println(constructor.getModifiers());//修饰符
        }
    }

    @Test
    public void testConstructor2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Student.class;
        //private Student(Integer id, String name, Integer age, String gender)
        Constructor constructor = clazz.getDeclaredConstructor(Integer.class, String.class, Integer.class, String.class);
        //在反射面前，私有的都可以访问
        constructor.setAccessible(true);
        //Student student = new Student(1, "zhansgan", 23, "男");
        Student student = (Student) constructor.newInstance(1, "zhangsan", 23, "男");
        System.out.println(student);
    }
}
